﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using JohnnySins.DAL.Repositories;
using JohnnySins.Entities;

namespace JohnnySins
{
    public class Global : System.Web.HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup

        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
           if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["IsDevelopmentEnvironment"])) return;

            System.Exception ex = Server.GetLastError();
            try
            {   
                var user = Membership.GetUser();
                
                string eventMessage = (ex.InnerException != null ? ex.InnerException.Message : ex.Message).Replace("'", "''");
                string stackTrace  = (ex.InnerException != null ? ex.InnerException.StackTrace : ex.StackTrace).Replace("'", "''");
                string currentUser = user != null ? user.UserName : "";
                string path = Context.Request.Path.Replace("'", "''");
                string queryString = Context.Request.QueryString.ToString();
                string browser = Context.Request.Browser.Browser;
                string userHostAddress =  Context.Request.UserHostAddress;
                string urlReferrer = (Context.Request.UrlReferrer != null ? Context.Request.UrlReferrer.ToString() : "");
               
                using (var repo = RepositoryFactory.ResolveRepository<LogRepository>())
                {
                    repo.SaveLog(eventMessage, stackTrace, currentUser, path, queryString, browser,
                        userHostAddress, urlReferrer);
                }      

                Response.Write("Unexpected error occurs. See log for details");
                Server.ClearError();
            }
            catch (Exception exNew)
            {
                Response.Write("Unexpected error occurs (" + ex.Message + " -> " + exNew.Message + ")<br/>" + ex.StackTrace);
                Server.ClearError();
            }      

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            var u = Membership.GetUser();
            if (u != null)
            {
                CurrentUsers.CanLogin(u.UserName);
            }
        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.
            var u = Membership.GetUser();
            if (u != null)
            {
                CurrentUsers.Remove(u.UserName);
            }
        }
    }
}
